package team.bluepen.supermarket.service;

import org.springframework.stereotype.Service;
import team.bluepen.supermarket.conf.KafkaProperties;
import team.bluepen.supermarket.data.database.SupermarketSystemDatabase;
import team.bluepen.supermarket.data.database.dao.ProductDao;
import team.bluepen.supermarket.data.entity.Product;
import team.bluepen.supermarket.kafka.KafkaTopics;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author RollW
 */
@Service
public class ProductPushService implements Consumer<List<Product>>, ProductProvider {
    private final ProductPusher productPusher;
    private final ProductDao productDao;
    private final List<Product> products;

    public ProductPushService(KafkaProperties kafkaProperties,
                              SupermarketSystemDatabase database) throws IOException {
        productPusher = new ProductPusher("/random_names.txt", kafkaProperties,
                KafkaTopics.PRODUCT_TOPIC, this);
        productPusher.start();
        productDao = database.getProductDao();
        products = new ArrayList<>();
        products.addAll(productDao.get());
    }

    public void stop() {
        productPusher.stop();
    }

    @Override
    public void accept(List<Product> products) {
        productDao.insert(products);
        this.products.addAll(products);
    }

    @Override
    public List<Product> getProducts() {
        return products;
    }

    @Override
    public Product getProductById(long id) {
        return productDao.getProductById(id);
    }
}
